<?php

namespace Frieza\Modules\Sensitive\Controllers;

use Encore\Admin\Widgets\Box;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Category;
use Doraemon\model\Tag\NewTagType as mTagTypeList;
use Doraemon\service\Tag\TagTypeList as sTagTypeList;
use Doraemon\service\AdmSensitive as sAdmSensitive;
use function Clue\StreamFilter\fun;

class WordController extends Controller
{
    const PAGE_SIZE = 50;

    public function cateList(Content $content)
    {
        $cateList = sAdmSensitive::getInstance()->getCateList();
        $gridModel = new pGridDataModel($cateList);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disablePagination();
            $grid->fixColumns(2, -2);
            $grid->disableFilter();

            $grid->column('tag', "标签");
            $grid->column('name', '名称');
            $grid->column('addTime', '添加时间')->display(function () {
                return date("Y-m-d H:i:s", $this->addTime);
            });
            $grid->actions(function ($actions) {
                // 去掉删除
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
                // append一个操作
                $actions->append('<a href="/admin/sensitive/cate/edit/' . $actions->row["tag"] . '"><i class="fa fa-eye">编辑</i></a>&nbsp;&nbsp;');
                $actions->append('<a href="/admin/sensitive/words/add/' . $actions->row["tag"] . '"><i class="fa fa-eye">敏感词添加</i></a>&nbsp;&nbsp;');
                $actions->append('<a href="/admin/sensitive/words/search/' . $actions->row["tag"] . '"><i class="fa fa-eye">敏感词删除</i></a>&nbsp;&nbsp;');
                // prepend一个操作
                $actions->append('<a href="/admin/sensitive/cate/delete/' . $actions->row["tag"] . '"><i class="fa fa-paper-plane">标签删除</i></a>');
            });
        });
        return $content
            ->header('敏感词分类')
            ->breadcrumb(
                ['text' => '分类列表', 'url' => '/admin/sensitive/cate']
            )
            ->body($listGrid->render());
    }


    public function delCate(Request $request, $tag = "", Content $content)
    {
        $res = sAdmSensitive::getInstance()->cateDel($tag);

        if ($res == 1) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/sensitive/cate')->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '删除成功',
        ]);
        return redirect('/admin/sensitive/cate')->with(compact('error'));
    }
    public function createCate(Request $request,  Content $content)
    {
        $ins = sAdmSensitive::getInstance();

        $formCate = new Form();
        $formCate->action('/admin/sensitive/cate/edit');
        $formCate->text('tag', "标签TAG")->required();
        $formCate->text('name', "标签名")->required();


        return $content
            ->header('敏感词标签')
            ->body($formCate->render());
    }
    public function editCate(Request $request, $tag = "",  $keyword = "-",$next = 0, Content $content)
    {
        Admin::js('/vendor/js/jquery-plugin/base64.js');
        $ins = sAdmSensitive::getInstance();
        $cateInfo = $ins->getCateInfo($tag);
        $keyword = $keyword!='-'?base64_decode($keyword):"-";
        $keywordEmpty = empty($keyword) || $keyword == "-";

        if ($keywordEmpty) {
            $result = $ins->getCateWordsPage($tag, $next);
            $next = $result['next'];
            $wordsList = $result["list"];
            $keyword = "";
        } else {
            $wordsList = $ins->getCateWordsSearch($tag, $keyword);
        }

        $isAddWords = strpos($request->url(), "words/add") !== false;
        $isWordSearch = strpos($request->url(), "words/search") !== false;

        $tab = new Tab();
        $formCate = new Form();
        $formCate->action('/admin/sensitive/cate/edit/' . $tag);
        $formCate->text('tag', "标签TAG")->default($cateInfo['tag'])->required();
        $formCate->text('name', "标签名")->default($cateInfo['name'])->required();
        $formCate->text("addTime", "添加时间")->default(date("Y-m-d H:i:s", $cateInfo['addTime']))->readonly();


        $wordsAddForm = new Form();
        $wordsAddForm->action('/admin/sensitive/words/edit/' . $tag);
        $wordsAddForm->textarea('words', "敏感词")->placeholder('请用回车分隔待添加的敏感词')->required();


        $wordsDelForm = new Form();
        $wordsDelForm->disableSubmit()->disableReset();
        $wordsDelForm->action('/admin/sensitive/words/delete/' . $tag);
        $wordsDelForm->textarea("keyword", "敏感词搜索")
            ->required()
            ->placeholder('请用回车分隔待筛选的敏感词列表')
            ->default($keyword)
            ->width("500px");
        $wordsDelForm->html(<<<SCRIPT
            <div class="btn-group pull-left">
                <a type="submit" class="btn btn-info pull-right words-search">筛选</a>
            </div>
            <div class="btn-group pull-right">
                <a type="submit" class="btn btn-info pull-right words-all">查看所有敏感词</a>
            </div>
            <script type="text/javascript">
            $(".words-search").click(function(){
                cateTag = "$tag";
                keyword = $("textarea[name=keyword]").val();
                keyword = $.base64.encode(keyword)
                window.location.href = "/admin/sensitive/words/search/"+cateTag+"/"+keyword;
            })
            $(".words-all").click(function(){
                cateTag = "$tag";
                window.location.href = "/admin/sensitive/words/search/"+cateTag;
            })
            </script>
SCRIPT
        );
        $wordsDelForm->fieldset("敏感词显示", function ($form) use ($wordsDelForm, $tag,$keywordEmpty, $wordsList, $isWordSearch, $next) {
            $wordsDelForm->checkbox("words", "敏感词列表")->options($wordsList)->canCheckAll();
            if ($keywordEmpty && $next > 0) {
                $nextPageHtml = <<<HTML
            <div class="btn-group pull-left">
                <a type="submit" class="btn btn-info pull-left words-next" data-next="$next">下一页</a>
            </div>
            <script type="text/javascript">
            $(".words-next").click(function(){
                window.location.href = "/admin/sensitive/words/search/$tag/-/$next"
            });
            </script>
HTML;

            }
            $wordsDelForm->html(<<<SCRIPT
            $nextPageHtml
            <div class="btn-group pull-right">
                <a type="submit" class="btn btn-info pull-right words-delete">删除</a>
            </div>
            <script type="text/javascript">
            $(".words-delete").click(function(){
                cateTag = "$tag";
                words = [];
                $(".words:checked").each(function(k,v){
                    words.push($(v).val());
                });
                $.post("/admin/sensitive/words/delete/"+cateTag,{"words":words.join("\\n")},function(result){
                    if (result.status == 1){
                        toastr.success('Message...', result.message)
                    }else{
                        toastr.error('Message...', result.message)
                    }
                     setTimeout(function(){
                            window.location.href="/admin/sensitive/words/search/"+cateTag;
                        },3000)
                },"json")
            })
            </script>
SCRIPT
            );
        });

        $tab->add('标签管理', $formCate, empty($tag));
        $tab->add('敏感词添加', $wordsAddForm, $isAddWords);
        $tab->add('敏感词删除', $wordsDelForm, $isWordSearch);


        return $content
            ->header('敏感词编辑')
            ->breadcrumb(
                ['text' => '分类列表', 'url' => '/admin/sensitive/cate/list']
            )
            ->body($tab->render());
    }

    public function editCatePost(Request $request, $tag = "", Content $content)
    {
        $postTag = $request->post("tag");
        //不可修改tag
        if (!empty($tag) && $postTag != $tag){
            $error = new MessageBag([
                'title' => '不可修改TAG ',
            ]);
            return back()->with(compact('error'));
        }

        if (empty($tag)){
            $tag = $postTag;
        }

        $name = $request->post("name");
        $res = sAdmSensitive::getInstance()->addCate($tag, $name);

        if ($res == 1) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/sensitive/cate')->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '添加失败 ',
        ]);
        return back()->with(compact('error'));
    }
    public function editCateWordsPost(Request $request, $tag = "", Content $content)
    {
        $words = $request->post("words");
        $words = str_replace("\r\n","\n",$words);
        $res = sAdmSensitive::getInstance()->addCateWords($tag, $words);
        if (empty($res)) {
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/sensitive/words/add/' . $tag)->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => $res,
        ]);
        return redirect('/admin/sensitive/words/add/' . $tag)->with(compact('error'));
    }

    public function deleteCateWordsPost(Request $request, $tag = "", Content $content)
    {
        $words = $request->post("words");
        $words = str_replace("\r\n","\n",$words);
        $words = trim($words, " ");

        $res = sAdmSensitive::getInstance()->delCateWords($tag, $words);
        if (empty($res)) {
            return response()->json([
                'status' => 1,
                'message' => "成功删除",
            ]);
        }
        return response()->json([
            'status' => 0,
            'message' => $res,
        ]);
    }

}
